//
//  AFDataBaseTools.m
//  AFFMDBTools_Example
//
//  Created by 张晓伟 on 2024/1/8.
//  Copyright © 2024 xywzxw. All rights reserved.
//

#import "AFDataBaseTools.h"
#import <FMDB.h>
#import <objc/runtime.h>

static FMDatabase *db;

@implementation AFDBQryModel


@end

@implementation AFDataBaseTools

/// 初始化FMDB服务，并始终开启数据库服务
/// - Parameter dbName: 数据库名称
+(void)configDataBaseWithDbName:(NSString *)dbName{
    // 1 获取数据库对象
    NSString *path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    path=[path stringByAppendingPathComponent:dbName];
    db = [FMDatabase databaseWithPath:path];
    if ([db open]) {
        [db executeUpdate:@"create table if not exists app_config(id integer PRIMARY KEY,key text,value text)"];
    }
}
/// 设置key-value值
/// - Parameters:
///   - value: value值
///   - key: key值
+(BOOL)setValue:(NSString *)value withKey:(NSString *)key{
    NSString *dbValue = [self getConfigValueWithKey:key];
    if(dbValue == nil){
        // 没有这个key，执行插入操作
        return [db executeUpdate:@"insert into app_config(key,value) values(?,?)",key,value];
    }else{
        // 有这个key，执行更新操作
        return [db executeUpdate:@"update app_config set value = ? where key = ?",value,key];
    }
}
/// 通过key获取指定的value值
/// - Parameter key: key值
+(NSString *)getConfigValueWithKey:(NSString *)key{
    FMResultSet *result = [db executeQuery:@"select * from app_config where key=?",key];
    NSString *dbValue = nil;
    while ([result next]) {
        dbValue = [result stringForColumn:@"value"];
    }
    return dbValue;
}
/// 获取存储的所有key-value值
+(NSDictionary *)getAllConfigs{
    FMResultSet *result = [db executeQuery:@"select * from app_config"];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    while ([result next]) {
        NSString *key = [result stringForColumn:@"key"];
        NSString *value = [result stringForColumn:@"value"];
        [param setValue:value forKey:key];
    }
    return param;
}
/// 删除指定key的键值对
/// - Parameter key: key
+(BOOL)delConfigWithKey:(NSString *)key{
    return [db executeUpdate:@"delete from app_config where key=?",key];
}

/// 清空所有key-value键值对
+(BOOL)clearAllConfig{
    return [db executeUpdate:@"delete from app_config"];
}

/// 插入数据
/// - Parameter model: 数据model
+(BOOL)insertModel:(NSObject *)model{
    unsigned int count = 0;
    Ivar *ivars = class_copyIvarList(model.class, &count);
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    for (int i = 0; i<count; i++) {
        // 取出i位置对应的成员变量
        Ivar ivar = ivars[i];
        // 查看成员变量
        const char *name = ivar_getName(ivar);
        NSString *key = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];
        key = [key substringFromIndex:1];
        id value = [model valueForKey:key];
        [param setValue:value==nil?@"":value forKey:key];
    }
    if([param[@"tableName"] length] == 0){
        NSLog(@"数据model中必须有tableName字段且不能为空");
        return false;
    }
    NSString *tableName = param[@"tableName"];
    [param removeObjectsForKeys:@[@"id",@"tableName"]];
    NSDictionary *dict = [self changeDictionaryToKeyValueString:param];
    NSString *createSql = [NSString stringWithFormat:@"create table if not exists %@(id integer PRIMARY KEY %@)",tableName,dict[@"keyParam"]];
    NSString *insertSql = [NSString stringWithFormat:@"insert into %@(%@) values (%@)",tableName,dict[@"key"],dict[@"value"]];
    BOOL res = [db executeUpdate:createSql];
    if(res){
        // 创建成功
        res = [db executeUpdate:insertSql];
    }
    return res;
}

+(NSArray *)queryListWithModel:(NSObject *)model qry:(AFDBQryModel *)qry{
    unsigned int count = 0;
    Ivar *ivars = class_copyIvarList(model.class, &count);
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    NSMutableArray *muarr = [NSMutableArray array];
    for (int i = 0; i<count; i++) {
        // 取出i位置对应的成员变量
        Ivar ivar = ivars[i];
        // 查看成员变量
        const char *name = ivar_getName(ivar);
        NSString *key = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];
        key = [key substringFromIndex:1];
        id value = [model valueForKey:key];
        [param setValue:value==nil?@"":value forKey:key];
    }
    if([param[@"tableName"] length] == 0){
        NSLog(@"数据model中必须有tableName字段且不能为空");
        return false;
    }
    NSString *tableName = param[@"tableName"];
    [param removeObjectsForKeys:@[@"tableName"]];
    
    NSString *paramStr = @"where ";
    for (NSString *key in [param allKeys]) {
        id value = [param objectForKey: key];
        if([value isKindOfClass:NSString.class] && ![value isEqualToString:@""]){
            paramStr = [NSString stringWithFormat:@"%@ %@ like '%%%@%%' and",paramStr,key,value];
        }
        if(([key isEqualToString:@"id"] && [value intValue] != 0)){
            paramStr = [NSString stringWithFormat:@"%@ %@ = %@ and",paramStr,key,value];
        }
    }
    if (qry.paramStr.length > 0) {
        paramStr = [NSString stringWithFormat:@"%@ %@ and",paramStr,qry.paramStr];
    }
    if(paramStr.length > 6){
        paramStr = [paramStr substringToIndex:paramStr.length - 4];
    }
    paramStr = [paramStr stringByAppendingString:@" ORDER BY id DESC"];
    if(qry.page != 0 && qry.rows != 0){
        paramStr = [paramStr stringByAppendingFormat:@"%@", [NSString stringWithFormat:@" limit %d offset %d",qry.rows,(qry.page-1)*qry.rows]];
    }
    NSString *sqlStr = [NSString stringWithFormat:@"SELECT * FROM %@ %@",tableName,paramStr];
    
    FMResultSet *result = [db executeQuery:sqlStr];
    while ([result next]) {
        NSMutableDictionary *obj = [NSMutableDictionary dictionary];
        for (NSString *key in [param allKeys]) {
            [obj setValue:[result stringForColumn:key] forKey:key];
        }
        [muarr addObject:obj];
    }
    return muarr;
}

/// 将键值转换为需要的内容
/// - Parameter dict: 数据
+(NSDictionary *)changeDictionaryToKeyValueString:(NSDictionary *)dict{
    NSString *key = @"";
    NSString *value = @"";
    NSString *keyParam = @"";
    for (NSString *k in dict) {
        keyParam = [NSString stringWithFormat:@"%@,%@ text",keyParam,k];
        key = [NSString stringWithFormat:@"%@,%@",key,k];
        value = [NSString stringWithFormat:@"%@,'%@'",value,dict[k]];
    }
    if(dict.count > 0){
        return @{@"key":[key substringFromIndex:1],@"keyParam":keyParam,@"value":[value substringFromIndex:1]};
    }
    return @{@"key":key,@"keyParam":keyParam,@"value":value};
}


@end
